package http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import API.LoginApi;
import dataprovider.normalDataProvider;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

/**
 * 基础类
 * 根据项目接口使用的协议，实现相关的请求
 *目前post请求只是表单方式提交
 */


public class HttpClientHelper 
{
	static String responseBody;
	static CloseableHttpClient httpclient = HttpClients.createDefault();
	
	/*public sratic JSONObject getJSONObjectByPost(String url) throws IOException //抛出异常
	{
		HttpPost httpPost = new HttpPost(url); //建立HttpPost对象
		//定义了一个list，该list的数据类型是NameValuePair,在发送post请求时用该list来存放参数。
		List<NameValuePair> data = new ArrayList<NameValuePair>();
		data.add(new BasicNameValuePair("signature", key));
		data.add(new BasicNameValuePair("phone", phone));
		data.add(new BasicNameValuePair("login_pwd", pwd));
	    httppost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8));   //组装请求Entity
	    CloseableHttpResponse response=HttpClient.execute(HttpPost);   //发送Post,并返回一个Response对象  
	    try{
	    	int status =response.getStatusLine().getStatusCode();
	    	if(status==200)
	    	{
	    		HttpEntity entity=response.getEntity();
	    		responseBody =EntityUtils.toString(entity);
	    		JSONObject jsonResult =JSONObject.fromObject(responseBody);
	    		//System.out.print(jsonResult);
	    		return jsonResult;
	    		}
	    	else{
	    		System.out.print("请求错误，状态码为：" + response.getStatusLine().getStatusCode());
	    		 throw new ClientProtocolException("意外的状态返回: " + status);    		
	    	}
	    	
	    }
	    finally {
	    	response.close();	
	    
	}*/
		
	public static JSONObject getJSONObjectByPost(String url,String phone,String passwd) throws IOException
    {
		
		HttpPost httppost = new HttpPost(url);	
		List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("phone", phone));
        data.add(new BasicNameValuePair("login_pwd", passwd));  //注意字段名一致
        
      //httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
        //组装请求Entity
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data);
        //UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
        httppost.setEntity(formEntity);   
        //HttpResponse response=new DefaultHttpClient().execute(httppost);
		//获取返回内容
		CloseableHttpResponse response = httpclient.execute(httppost);       //发送Post,并返回一个Response对象       
	    try {
		int status = response.getStatusLine().getStatusCode();
	    if (status == 200) {
	    	//获取内容，并转换成String类型
	    	HttpEntity entity = response.getEntity();	       
	    	responseBody = EntityUtils.toString(entity);	    	
	    	//转换成json格式，方便后面做验证
 	       	JSONObject jsonResult =JSONObject.fromObject(responseBody); 
 	       	System.out.print(jsonResult);
            return jsonResult; 	                  
	     } 
	    else {
	        System.out.print("请求错误，状态码为：" + response.getStatusLine().getStatusCode());
	        throw new ClientProtocolException("意外的状态返回: " + status);
	     } 
	    }
	    finally {
	    	response.close();	    	
	    }
    }
	

	

	public static JSONObject getJSONObjectByGet(String url) throws IOException
	{
				
        HttpGet httpget = new HttpGet(url);
		//获取返回内容
		CloseableHttpResponse response = httpclient.execute(httpget);              
	    try {
		int status = response.getStatusLine().getStatusCode();
	    if (status == 200) {
	    	//获取内容，并转换成String类型
	    	HttpEntity entity = response.getEntity();	       
	    	responseBody = EntityUtils.toString(entity);	    	
	    	//转换成json格式，方便后面做验证
 	       	JSONObject jsonResult =JSONObject.fromObject(responseBody); 
 	       
            return jsonResult; 	                  
	     } 
	    else {
	        System.out.print("请求错误，状态码为：" + response.getStatusLine().getStatusCode());
	        throw new ClientProtocolException("意外的状态返回: " + status);
	     } 
	    }
	    finally {
	    	response.close();
	    }
	
	}
	
	public static void closeClient() throws IOException 
	{
		httpclient.close();
	}

	
	public static HttpClient Login(HttpClientHelper httphelper) {
		// TODO Auto-generated method stub
		String url= normalDataProvider.setUrl();
		String phone= normalDataProvider.setPhone();
		String passwd= normalDataProvider.setPasswd();
		LoginApi.Login(url,phone,passwd);
		return httpclient;
	}
}
